<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" v-show="showSearch" label-width="68px">

      <el-form-item label="企业名称" prop="corpId">
        <el-select v-model="queryParams.corpId" placeholder="请选择企业名称" filterable @change="handleHospdepChange" style="">
          <el-option v-for="item in qiyelist" :key="item.corpId" :label="item.corpName" :value="item.corpId" />
        </el-select>
      </el-form-item>
      <!-- <el-form-item label="科室名称" prop="deptName">
        <el-input v-model="queryParams.deptName" placeholder="请输入科室名称" clearable @keyup.enter.native="handleQuery" />
      </el-form-item>

      <el-form-item label="医院码" prop="hospitalCode">
        <el-input v-model="queryParams.hospitalCode" placeholder="请输入医院码" clearable @keyup.enter.native="handleQuery" />
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
      </el-form-item> -->
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button type="primary" plain icon="el-icon-plus" size="mini" @click="handleAdd"
          v-hasPermi="['digitaldoctorops:department:add']">新增</el-button>

      </el-col>
      <el-col :span="1.5">
        <el-button type="primary" :disabled="queryParams.corpId == ''" plain icon="el-icon-plus" size="mini"
          @click="handlegeng" v-hasPermi="['digitaldoctorops:department:add']">更新科室</el-button>

      </el-col>
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="departmentList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column label="医院名称" align="center" prop="hospitalName" />
      <el-table-column label="科室名称" align="center" prop="deptName" />
      <el-table-column label="关联医生人数" align="center" prop="email" />

      <el-table-column label="运营人员" align="center" prop="name" />
      <el-table-column label="平台科室id" align="center" prop="platDeptId" />
      <el-table-column label="排序" align="center" prop="orderNum" />

      <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
        <template slot-scope="scope">
          <el-button size="mini" type="text" icon="el-icon-edit" @click="handleUpdate(scope.row)"
            v-hasPermi="['digitaldoctorops:department:edit']">修改</el-button>
          <el-button size="mini" type="text" icon="el-icon-delete" @click="handleDelete(scope.row)"
            v-hasPermi="['digitaldoctorops:department:remove']">删除</el-button>
        </template>
      </el-table-column>
    </el-table>

    <pagination v-show="total > 0" :total="total" :page.sync="queryParams.pageNum" :limit.sync="queryParams.pageSize"
      @pagination="getList" />

    <!-- 添加或修改科室管理对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="500px" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="120px">
        <el-form-item label="企业名称" prop="corpName" v-if="form.corpName">
          <el-input v-model="form.corpName" disabled placeholder="请输入企业名称" />
        </el-form-item>
        <el-form-item label="科室名称" prop="deptName">
          <el-input v-model="form.deptName" placeholder="请输入科室名称" />
        </el-form-item>
        <el-form-item label="运营人员" prop="userId">
          <el-select v-model="form.userId" placeholder="请选择运营人员" filterable style="width: 100%;">
            <el-option v-for="item in yunyinglist" :key="item.userId" :label="item.nickName" :value="item.userId" />
          </el-select>
        </el-form-item>
        <el-form-item label="排序" prop="orderNum">
          <el-input v-model="form.orderNum" type="number" placeholder="请输入排序" />
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { listDepartment, getDepartment, delDepartment, addDepartment, updateDepartment, getqiye, pigeng, yunyingrenyuan } from "@/api/digitaldoctorops/department";


export default {
  name: "Department",
  data() {
    return {
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 科室管理表格数据
      departmentList: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        deptId: null,
        deptName: null,
        hospitalId: null,
        hospitalCode: null,
        parentId: null,
        deptType: null,
        sort: null,
        departmentLogo16: null,
        departmentLogo: null
      },
      // 表单参数
      form: {
        deptName: '',  // 初始化为空字符串
        userId: null,
        corpId: null,
        corpName: '',
        orderNum: null
      },
      // 表单校验
      rules: {
        deptId: [
          { required: true, message: "科室id不能为空", trigger: "blur" }
        ],
        deptName: [
          { required: true, message: "科室名称不能为空", trigger: "blur" }
        ],
        orderNum: [
          { required: true, message: "排序不能为空", trigger: "blur" }
        ],
        parentId: [
          { required: true, message: "父级id不能为空", trigger: "blur" }
        ],
        deptType: [
          { required: true, message: "科室类型，如2专病门诊，1普通门诊不能为空", trigger: "change" }
        ],
      },
      qiyelist: "",
      yunyinglist: []
    };
  },
  created() {
    this.getqiyedata()
    // this.getyunying()
  },
  methods: {
    getyunying() {
      yunyingrenyuan({}).then(res => {
        this.yunyinglist = res.data
      })
    },
    handlegeng() {
      this.loading = true
      pigeng({
        corpId: this.queryParams.corpId
      }).then(res => {
        this.$modal.msgSuccess("更新成功");
        this.queryParams.pageNum = 1
        this.loading = false

        this.getList()
      }).catch(() => {
        this.loading = false
      })
    },
    handleHospdepChange() {

      this.getList()
    },
    getqiyedata() {
      getqiye({}).then(res => {
        if (res.data.length > 0) {
          this.qiyelist = res.data
          this.queryParams.corpId = this.qiyelist[0].corpId
          this.form.corpName = this.qiyelist[0].corpName
          this.form.corpId = this.qiyelist[0].corpId
          this.getList();
        }


      })
    },
    /** 查询科室管理列表 */
    getList() {
      this.loading = true;
      listDepartment(this.queryParams).then(response => {
        this.departmentList = response.rows;
        this.total = response.total;
        this.loading = false;
      });
    },
    // 取消按钮
    cancel() {
      this.form.deptName = ""
      this.open = false;
      this.reset();
    },
    // 表单重置
    reset() {
      this.form = {
        deptId: null,
        deptName: '', // 确保重置时包含 deptName
        userId: null,
        orderNum: null,
        // corpId: this.form.corpId, // 保留当前企业ID
        // corpName: this.form.corpName
      };
      this.resetForm("form");
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      this.handleQuery();
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.deptId)
      this.single = selection.length !== 1
      this.multiple = !selection.length
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset();
      this.form.deptName = ""
      this.getyunying()

      this.open = true;
      this.qiyelist.forEach(el => {
        if (el.corpId == this.queryParams.corpId) {
          this.form.corpName = el.corpName
          this.form.corpId = el.corpId
        }
      });
      this.title = "添加科室管理";
      console.log(this.form, "sddkh")
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset();
      this.getyunying();
      // 创建新对象，复制row的属性
      this.form = { ...row }; // 使用展开运算符
      // 或者使用 Object.assign
      // this.form = Object.assign({}, row);

      this.open = true;
      this.qiyelist.forEach(el => {
        if (el.corpId == this.queryParams.corpId) {
          this.form.corpName = el.corpName;
          this.form.corpId = el.corpId;
        }
      });
      this.title = "修改科室管理";
    },
    /** 提交按钮 */
    submitForm() {
      this.$refs["form"].validate(valid => {
        if (valid) {
          if (this.title == "添加科室管理") {
            addDepartment(this.form).then(response => {
              this.$modal.msgSuccess("新增成功");
              this.open = false;
              this.form.deptName = ""

              this.getList();
            });
          }
          if (this.title == "修改科室管理") {
            let obj = {}
            obj.deptId = this.form.deptId
            obj.deptName = this.form.deptName
            obj.userId = this.form.userId
            obj.orderNum = this.form.orderNum
            updateDepartment(obj).then(response => {
              this.$modal.msgSuccess("修改成功");
              this.open = false;
              this.form.deptName = ""

              this.getList();
            });
          }
          // if (this.form.id != null) {
          //   updateDepartment(this.form).then(response => {
          //     this.$modal.msgSuccess("修改成功");
          //     this.open = false;
          //     this.getList();
          //   });
          // } else {
          //   addDepartment(this.form).then(response => {
          //     this.$modal.msgSuccess("新增成功");
          //     this.open = false;
          //     this.getList();
          //   });
          // }
        }
      });
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const ids = row.deptId || this.ids;
      this.$modal.confirm('是否确认删除科室？').then(function () {
        return delDepartment(ids);
      }).then(() => {
        this.getList();
        this.$modal.msgSuccess("删除成功");
      }).catch(() => { });
    },
    /** 导出按钮操作 */
    handleExport() {
      this.download('digitaldoctorops/department/export', {
        ...this.queryParams
      }, `department_${new Date().getTime()}.xlsx`)
    }
  }
};
</script>
